﻿using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms.Integration;
using System.Windows.Media;
using FormView.UI.AlertView;
using FxFlowWindowBase.Win;

namespace FormView.UI
{
	public abstract class FormWindowBase : FlowWindow
	{
		/// <summary>
		/// 默认内置组件的背景色
		/// </summary>
		public static readonly SolidColorBrush DefaultBgColor = new SolidColorBrush(ParseColorStr("#77000000"));

		/// <summary>
		/// 默认内置组件的前景色
		/// </summary>
		public static readonly SolidColorBrush DefaultForeColor = new SolidColorBrush(Colors.Yellow);

		/// <summary>
		/// 所有表单式窗体链
		/// </summary>
		protected static Dictionary<string, LinkedList<FormWindowBase>> WindowChains =
			new Dictionary<string, LinkedList<FormWindowBase>>();


		/// <summary>
		/// 等待窗体关闭信号量
		/// </summary>
		private SemaphoreSlim mSemaphore = new SemaphoreSlim(0);

		public FormWindowBase(string @namespace)
		{
			if (!WindowChains.ContainsKey(@namespace))
			{
				WindowChains.Add(@namespace, new LinkedList<FormWindowBase>());
			}
			WindowChains[@namespace].AddLast(this);

			Topmost = true;
			AutoScrollToEnd = false;
			WindowStartupLocation = WindowStartupLocation.Manual;
			Opacity = 0.8;
			ResizeMode = ResizeMode.CanResizeWithGrip;
			Closed += (sender, args) => mSemaphore.Release();

			ElementHost.EnableModelessKeyboardInterop(this);
		}

		protected void EnableFooterBar()
		{
			AlertFooterBar alertFooterBar = new AlertFooterBar("确 定", "取 消");
			alertFooterBar.OnClickNegative += () => CloseWin(true);
			alertFooterBar.OnClickPositive += () => CloseWin(false);
			SetFooterBar(alertFooterBar);
			SwitchFooterBarState(Visibility.Visible);
		}

		private void CloseWin(bool userClose)
		{
			IsUserClose = userClose;
			Close();
		}

		protected internal static void CloseAllWindow(string @namespace)
		{
			LinkedList<FormWindowBase> wins;
			bool hasVal = WindowChains.TryGetValue(@namespace, out wins);
			if (!hasVal) return;

			foreach (var windowBase in wins)
			{
				windowBase.Close();
			}

			WindowChains.Remove(@namespace);
		}

		protected abstract FormResult GetFormResult();

		protected abstract FormResult OnUserCloseWinGetResult();

		/// <summary>
		/// 等待窗体关闭获取表单窗体结果
		/// </summary>
		/// <returns>成功返回结果，用户取消返回null</returns>
		public virtual async Task<FormResult> WaitForResult()
		{
			if (IsClosed)
			{
				return  IsUserClose ? OnUserCloseWinGetResult() : GetFormResult();
			}

			await mSemaphore.WaitAsync();

			return IsUserClose ? OnUserCloseWinGetResult() : GetFormResult();
		}

	}
}
